package com.losdun.aftersales.liteweb;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.losdun.aftersales.liteweb.config.LitewebConfig;
import com.losdun.aftersales.liteweb.vo.OutputVo;
import com.losdun.aftersales.liteweb.vo.ProjectVo;
import com.losdun.aftersales.liteweb.vo.TaskVo;
import com.losdun.aftersales.liteweb.vo.req.OutputQueryReq;
import com.losdun.aftersales.liteweb.vo.req.ProjectQueryReq;
import com.losdun.aftersales.liteweb.vo.req.TaskQueryReq;
import com.losdun.aftersales.liteweb.vo.res.OutputQueryResp;
import com.losdun.aftersales.liteweb.vo.res.ProjectQueryResp;
import com.losdun.aftersales.liteweb.vo.res.TaskQueryResp;
import com.losdun.common.core.redis.RedisCache;
import com.losdun.common.utils.EncryptUtils;
import com.losdun.common.utils.http.LosdunHttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author Sword.Ye
 * @Date 2025/8/22
 * 小工单客户端
 **/
@Component
@Slf4j
public class LitewebClient {

    public static final String LITEWEB_AUTH_TOKEN_KEY = "liteweb_auth_token";
    public static final String SUCCESS_STATUS_CODE = "01000000";
    @Autowired
    private LitewebConfig litewebConfig;
    @Autowired
    private RedisCache redisCache;

    //工厂代码 040809

    //登录接口
    private final String LOGIN_URL="/api/user/v1/users/_login";
    //工单查询接口
    private final String PROJECT_QUERY_URL="/api/dytin/external/project/queryList3";
    //任务查询接口
    private final String TASK_QUERY_URL="/api/dytin/external/task/queryList2";
    //报工查询接口
    private final String OUTPUT_QUERY_URL="/api/dytin/external/output/queryList3";

    /**
     * 登录接口
     * @return
     * @throws Exception
     */
    public String login() throws Exception{
        if(redisCache.getCacheObject(LITEWEB_AUTH_TOKEN_KEY)!=null){
            return redisCache.getCacheObject(LITEWEB_AUTH_TOKEN_KEY);
        }

        Map<String, String> headers = new HashMap<>();
        headers.put("X-CLIENT", "lite-web");
        headers.put("Content-Type", "application/json");

        Map<String, Object> body = new HashMap<>();
        body.put("phone", litewebConfig.getPhone());
        body.put("password", EncryptUtils.encryptSHA3224(litewebConfig.getPassword()));
        String resp = LosdunHttpUtils.sendPost(buildUrl(LOGIN_URL), headers, JSON.toJSONString(body));
        JSONObject jsonObj = JSON.parseObject(resp);
        if(jsonObj.getInteger("statusCode")==200){
            String token = jsonObj.getString("data");
            log.info("小工单登录成功,token={}", token);
            redisCache.setCacheObject(LITEWEB_AUTH_TOKEN_KEY, token);
            return token;
        }else{
            log.error("小工单登录失败!err:{}", jsonObj.getString("message"));
            throw new RuntimeException("小工单登录失败:"+jsonObj.getString("message"));
        }
    }

    public List<ProjectVo> queryProjectList(ProjectQueryReq req){
        try {
            login();
            String resp=LosdunHttpUtils.sendPost(buildUrl(PROJECT_QUERY_URL),generateHeaders(),JSON.toJSONString(req));
            ProjectQueryResp projectQueryResp = JSON.parseObject(resp, ProjectQueryResp.class);
            log.info("projectQueryResp = {}", projectQueryResp);
            if(projectQueryResp.getCode().equals(SUCCESS_STATUS_CODE)){
                return projectQueryResp.getData();
            }else{
                log.warn("查询工单失败!code:{},msg:{}", projectQueryResp.getCode(), projectQueryResp.getMsg());
            }
        } catch (Exception e) {
            log.error("查询工单错误!message:{}", e.getMessage(), e);
        }
        return null;
    }

    public List<TaskVo> queryTaskList(TaskQueryReq req){
        try {
            login();
            String resp=LosdunHttpUtils.sendPost(buildUrl(TASK_QUERY_URL),generateHeaders(),JSON.toJSONString(req));
            TaskQueryResp taskQueryResp = JSON.parseObject(resp, TaskQueryResp.class);
            log.info("taskQueryResp = {}", taskQueryResp);
            if(taskQueryResp.getCode().equals(SUCCESS_STATUS_CODE)){
                return taskQueryResp.getData();
            }else{
                log.warn("查询工单任务失败!code:{},msg:{}", taskQueryResp.getCode(), taskQueryResp.getMsg());
            }
        } catch (Exception e) {
            log.error("查询工单任务错误!message:{}", e.getMessage(), e);
        }
        return null;
    }
    public List<OutputVo> queryOutputList(OutputQueryReq req){
        try {
            login();
            String resp=LosdunHttpUtils.sendPost(buildUrl(OUTPUT_QUERY_URL),generateHeaders(),JSON.toJSONString(req));
            OutputQueryResp outQueryResp = JSON.parseObject(resp, OutputQueryResp.class);
            log.info("outQueryResp = {}", outQueryResp);
            if(outQueryResp.getCode().equals(SUCCESS_STATUS_CODE)){
                return outQueryResp.getData();
            }else{
                log.warn("查询报工任务失败!code:{},msg:{}", outQueryResp.getCode(), outQueryResp.getMsg());
            }
        } catch (Exception e) {
            log.error("查询报工任务错误!message:{}", e.getMessage(), e);
        }
        return null;
    }

    private Map<String,String> generateHeaders(){
        Map<String,String> headers = new HashMap<>();
        headers.put("X-AUTH", redisCache.getCacheObject(LITEWEB_AUTH_TOKEN_KEY));
        headers.put("Content-Type", "application/json");
        return headers;
    }

    private String buildUrl(String path) {
        return litewebConfig.getUrl() + path;
    }


}
